import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, Repository } from 'typeorm';
import { User } from './models/user.entity';
import { encryptPassword } from '../../util';
import { ENCRYPT_SALT } from '../../constant';
import { Result } from '../../dto/result.type';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private UserRepository: Repository<User>,
  ) {}

  // 新增一个用户
  async createUser(entity: DeepPartial<User>): Promise<Result> {
    // 判断是否已经存在该用户
    if (entity.account) {
      const user = await this.UserRepository.findOne({
        where: {
          account: entity.account,
        },
      });
      if (user) return { code: false, message: '用户名已存在' };
    }

    // 加密
    entity.password = encryptPassword(entity.password, ENCRYPT_SALT);

    const res = await this.UserRepository.insert(entity);
    return {
      message: !!res ? '新增成功' : '新增失败',
      code: !!res,
    };
  }

  // 删除一个用户
  async delUser(id: string): Promise<boolean> {
    const res = await this.UserRepository.delete(id);
    return res.affected > 0;
  }

  // 更新一个用户其他信息
  async updateUser(id: string, entity: DeepPartial<User>): Promise<Result> {
    const res = await this.UserRepository.update(id, entity);
    const result = res.affected > 0;
    return result
      ? {
          message: '更新成功',
          code: true,
        }
      : {
          message: '更新失败',
          code: false,
        };
  }

  // 查询一个用户通过id
  async findUserById(id: string): Promise<User> {
    return await this.UserRepository.findOne({
      where: {
        id,
      },
    });
  }

  // 查询一个用户通过手机号
  async findUserByTel(tel: string): Promise<User> {
    return await this.UserRepository.findOne({
      where: {
        tel,
      },
    });
  }

  // 更新一个用户的验证码
  async updateUserCode(id: string, code: string): Promise<Result> {
    const res = await this.UserRepository.update(id, {
      code,
      codeCreateAt: new Date(),
    });
    const result = res.affected > 0;
    return result
      ? {
          message: '更新成功',
          code: true,
        }
      : {
          message: '更新失败',
          code: false,
        };
  }
}
